package com.example.demo.bean;

import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public final class BuildBaseSql {

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    public static String getWhere(String timestampField, String time, String sourceSql) throws ParseException {
        if (StringUtils.isEmpty(timestampField) || StringUtils.isEmpty(time)) {
            return "";
        }

        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(time));
        long end = get_D_Plaus_1(cal);

        String endTime = sdf.format(end);
        StringBuilder sb = new StringBuilder();
        String keyWord = " where ";

        if(!StringUtils.isEmpty(sourceSql) && sourceSql.toLowerCase().contains("where")){
            keyWord = " and ";
        }

        sb.append(keyWord)
                .append(timestampField)
                .append(">='")
                .append(time)
                .append("'")
                .append(" and ")
                .append(timestampField).append(" <='").append(endTime).append("'");
        return sb.toString();
    }

    public static String getLimit(int limit) {
        if (limit <= 0) {
            return "";
        } else {
            return " limit " + limit;
        }
    }

    public static long get_D_Plaus_1(Calendar c) {
        c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) + 1);
        return c.getTimeInMillis();
    }
}
